﻿using System.Collections.Generic;
using System.Linq;
using Aquarinum.Base.Infrastructure.Ioc;
using Aquarinum.Base.Infrastructure.WebSocket.Interface;
using Aquarinum.Base.Infrastructure.WebSocket.InterfaceImp;
using Aquarinum.Base.Infrastructure.WebSocket.MessageHandler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Aquarinum.Base.Infrastructure.WebSocket.Extensions
{
    public static class WebSocketManagerExtensions
    {
        /// <summary>
        ///     注册服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="customRegisterStrategys">自定义注册策略</param>
        /// <returns></returns>
        public static IServiceCollection AddWebSocketManager(this IServiceCollection services,
            IList<ServiceRegisterStrategy> customRegisterStrategys = null)
        {
            //注册websocket连接容器单例
            AquainumContainer.Register(typeof(WebSocketConnectionContainer), typeof(WebSocketConnectionContainer),
                EnumLifetimeScope.SingleInstance);
            //webSokcet请求中转
            AquainumContainer.Register(typeof(WebSocketRequestTransfer), typeof(IWebSocketRequestTransfer),
                EnumLifetimeScope.SingleInstance);
            //消息发送代理
            AquainumContainer.Register(typeof(DefaultMessageSendProxy), typeof(IMessageSendProxy));

            ////注册缓存组件
            //AquainumContainer
            //    .Register<DefaultCachingProvider<WebsocketMessageDto>, ICachingProvider<WebsocketMessageDto>>();
            //AquainumContainer.Register<DefaultCachingProvider<ClientEntity>, ICachingProvider<ClientEntity>>();

            //消息缓存
            AquainumContainer.Register(typeof(DefaultMessageCacheHandler), typeof(IMessageCacheHandler));
            //分组信息缓存
            AquainumContainer.Register(typeof(DefaultClientInfosProvider), typeof(IClientInfosProvider));
            //默认处理策略（自动）

            MessageHandleStrategyFactory.GetInstance().AutoRegisterAllStrategys();
            //注册处理策略（手动）
            //MessageHandleStrategyFactory.GetInstance().Register<>();

            //IWebSocketServerSeeker
            //注册自定义对象
            if (customRegisterStrategys != null && customRegisterStrategys.Any())
                foreach (var customRegister in customRegisterStrategys)
                    if (customRegister.ImpType.GetInterfaces()
                            .Any(y => y.Name == typeof(IMessageHandleStrategy).Name) && customRegister.ImpType.IsClass)
                    {
                        var propertyAttribute = (HandlerPropertyAttribute)
                            customRegister.ImpType.GetCustomAttributes(typeof(HandlerPropertyAttribute), false)
                                .FirstOrDefault();


                        if (propertyAttribute != null && !string.IsNullOrEmpty(propertyAttribute.MessageType))
                            MessageHandleStrategyFactory.GetInstance().Register(propertyAttribute.MessageType,
                                customRegister.ImpType, customRegister.LifetimeScope);
                        else
                            MessageHandleStrategyFactory.GetInstance().Register(
                                customRegister.ImpType.Name.ToLower().Replace("messagehandlestrategy", string.Empty),
                                customRegister.ImpType); //此处约定由于配置，所有策略类型命名规则为 ：消息类型+MessageHandleStrategy
                    }
                    else
                    {
                        AquainumContainer.Register(customRegister.AbstractType, customRegister.ImpType,
                            customRegister.LifetimeScope);
                    }


            return services;
        }

        public static IApplicationBuilder MapWebSocketManager(this IApplicationBuilder applicationBuilder, string route)
        {
            applicationBuilder.Map(
                $"/{route}",
                app => app.UseMiddleware<WebSocketManagerMiddleware>( /*IocContainer.Resolve(socketHandlType)*/));

            return applicationBuilder;
        }
    }
}